package acheng1314.cn.a3dbuild2.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.acheng.achengutils.mvp.view.BaseActivity;
import com.acheng.achengutils.utils.AppUtils;
import com.acheng.achengutils.utils.ImageUtils;
import com.acheng.achengutils.utils.SPHelper;
import com.acheng.achengutils.utils.StringUtils;
import com.acheng.achengutils.widgets.MustDoThingDailog;

import java.io.File;
import java.util.Map;

import acheng1314.cn.a3dbuild2.MyApplication;
import acheng1314.cn.a3dbuild2.R;
import acheng1314.cn.a3dbuild2.bean.ModelUrlBean;
import acheng1314.cn.a3dbuild2.service.LocationService;
import acheng1314.cn.a3dbuild2.view.activity.presenter.AppWebActivityPresenter;
import acheng1314.cn.a3dbuild2.view.activity.viewcontroller.AppWebActivityViewController;
import acheng1314.cn.a3dbuild2.widgets.MyProgressDialog;


/**
 * 超级船东内置浏览器，重写WebView的setWebViewClient方法，通过拦截约定URL做对应的功能
 *
 * @author acheng
 *         created by acheng at 2016年3月7日17:34:25
 */
public class AppWebActivity extends BaseActivity<AppWebActivityPresenter, AppWebActivityViewController> implements AppWebActivityViewController {

    private static String GET_ID_ERRO = "-1"; //为获取到文章的ID的标识码
    private String urlStr = "";
    private WebSettings settings;
    private TextView mTv_goback;
    private WebView webView;
    private ImageView mIv_back;
    private String url;
    private MyProgressDialog myProgressDialog;
    private Map<String, String> urlSplitMap;


    private int TAKE_PHOTO_WITH_DATA = 8;

    private Intent bindIntent;
    private String modelUrl;
    private ModelUrlBean modelUrlBean;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case R.id.doSuccess: {
                    if (null == urlSplitMap) {
                        new MustDoThingDailog("提示", "获取数据失败", getContext(), new MustDoThingDailog.NeedDoThing() {
                            @Override
                            public void mustDoThings() {
                                MyApplication.getInstance().outLog(TAG, "这是3D模型上面的点击事件");
                            }
                        });
                        return;
                    }
                    new MustDoThingDailog(urlSplitMap.get("title"), "是否拍照上传图片？(" + urlSplitMap.get("title") + ")", getContext(), new MustDoThingDailog.NeedDoThing() {
                        @Override
                        public void mustDoThings() {
                            /**
                             * mid:15812
                             * title:column
                             * intro:柱子
                             * posi:(0,0,-20.5629655)
                             * size:(40.47506,20.946002,41.125931)
                             * uprice:200.0000
                             * state:3
                             * Created by pang on 16/10/17.
                             */

                            if (null == modelUrlBean) modelUrlBean = new ModelUrlBean();

                            modelUrlBean.setMid(urlSplitMap.get("mid"));
                            modelUrlBean.setUid(SPHelper.getString(getContext(), getString(R.string.user), getString(R.string.userId)));
                            modelUrlBean.setTitle(urlSplitMap.get("title"));
                            modelUrlBean.setIntro(urlSplitMap.get("intro"));
                            modelUrlBean.setPosi(urlSplitMap.get("posi"));
                            modelUrlBean.setSize(urlSplitMap.get("size"));
                            modelUrlBean.setUprice(urlSplitMap.get("uprice"));
                            modelUrlBean.setState(urlSplitMap.get("state"));

//                    SPHelper.setString(LocationService.this, getString(R.string.gpsValues), getString(R.string.latitude), location.getLatitude() + "");
//                    SPHelper.setString(LocationService.this, getString(R.string.gpsValues), getString(R.string.longitude), location.getLongitude() + "");
//                    SPHelper.setString(LocationService.this, getString(R.string.gpsValues), getString(R.string.altitude), location.getAltitude() + "");
                            String altituStr = SPHelper.getString(getContext(), getString(R.string.gpsValues), getString(R.string.altitude));
                            String latituStr = SPHelper.getString(getContext(), getString(R.string.gpsValues), getString(R.string.latitude));
                            String lontituStr = SPHelper.getString(getContext(), getString(R.string.gpsValues), getString(R.string.longitude));
                            modelUrlBean.setAltitu(StringUtils.isEmpty(altituStr) ? "-1" : altituStr);
                            modelUrlBean.setLatitu(StringUtils.isEmpty(latituStr) ? "-1" : latituStr);
                            modelUrlBean.setLongit(StringUtils.isEmpty(lontituStr) ? "-1" : lontituStr);
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, TAKE_PHOTO_WITH_DATA);
                        }
                    });


                }

                break;
                default:
                    break;
            }
        }

    };

    @Override
    public void showProgressD() {
        if (null == myProgressDialog)
            myProgressDialog = new MyProgressDialog("加载中", "正在加载数据···", getContext());
        else
            myProgressDialog.show();
    }

    @Override
    public void disProgressD() {
        if (null != myProgressDialog)
            myProgressDialog.dismiss();
    }

    @Override
    public void showDailog(String msg) {
        new MustDoThingDailog("提示", msg, getContext(), new MustDoThingDailog.NeedDoThing() {
            @Override
            public void mustDoThings() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode != TAKE_PHOTO_WITH_DATA) {
            return;
        }
        if (resultCode != RESULT_OK) {
            return;
        }
        if (null == data) {
            showDailog("拍照失败，请检查手机");
            return;
        }
//        Intent intent = new Intent(getContext(), UploadPicActivity.class);
//        intent.putExtras(data);
//        intent.putExtra("url", url);
//        startActivity(intent);
        Bitmap photo1 = data.getParcelableExtra("data");
        File file = ImageUtils.bitmap2SamllFile(getContext(), photo1, 200, 400, false);

        mPresenter.uploadPic(file.getAbsolutePath(), modelUrlBean);

    }

    @Override
    public void onBackPressed() {
        webViewGoBack();
    }

    /**
     * 内置浏览器能否返回。
     */
    private void webViewGoBack() {
        if (myProgressDialog != null && myProgressDialog.isShowing()) {
            //关闭下拉刷新控件的刷新状态//开启下拉刷新控件的刷新状态
            disProgressD();
            return;
        }
        if (webView.canGoBack()) { //从界面创建后到现在，有历史记录可以返回
            webView.goBack();
        } else {
            finish();   //没有历史记录直接退出
        }
    }

    @Override
    protected AppWebActivityPresenter initPresenter() {
        return new AppWebActivityPresenter(this);
    }

    @Override
    protected void initEvent() {

        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webViewGoBack();
            }
        });
        ;
        findViewById(R.id.mTv_gohome).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.loadUrl(webView.getUrl());
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        bindIntent = new Intent(getContext(), LocationService.class);
        startService(bindIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != bindIntent) {
            stopService(bindIntent);
        }
    }

    @Override
    protected void initView() {

      /*  url = getIntent().getExtras().getString(getString(R.string.url));
        modelUrlBean = (ModelUrlBean) getIntent().getSerializableExtra("urlBean");*/

        webView = (WebView) findViewById(R.id.mWeb_refresh);

        mTv_goback = (TextView) findViewById(R.id.mTv_goback);
        mIv_back = (ImageView) findViewById(R.id.back);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
        webView.setWebViewClient(new mWebViewClient());    //设置webView的连接控制器


        webView.clearCache(true);
        webView.clearHistory();
        webView.clearFormData();
        webView.clearMatches();

        settings = webView.getSettings();
        settings.setUserAgentString(String.format("%s |%s", settings.getUserAgentString(), "ChengApp"));
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setSupportZoom(true);
        settings.setJavaScriptEnabled(true);// 表示支持js
        settings.setBuiltInZoomControls(true);// 显示放大缩小按钮
        settings.setUseWideViewPort(true);// 支持双击缩放

     /*   if (!StringUtils.isEmpty(url)) {
            webView.loadUrl(url);
            MyApplication.getInstance().outLog("输出", url);
        } else {

        }*/
        webView.loadUrl("http://101.132.99.158/res/projects/admin/test/mytest.FBX");

    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_app_web;
    }

    /**
     * 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
     */
    class mWebViewClient extends WebViewClient {
        // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            showProgressD();

            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.e("===",url);
            if(!url.equals(AppWebActivity.this.url)){
               mIv_back.setVisibility(View.VISIBLE);
            }else{
                mIv_back.setVisibility(View.GONE);
            }
            if (view.getTitle() == null && "找不到网页".equals(view.getTitle()) && view.getTitle().contains("http")) {
                mTv_goback.setText(String.format("用户：%s", SPHelper.getString(getContext(), getString(R.string.user), getString(R.string.username), "默认用户")));       //给Title设置标题
            } else if (url.equals(AppWebActivity.this.url)) {
                mTv_goback.setText(String.format("用户：%s", SPHelper.getString(getContext(), getString(R.string.user), getString(R.string.username), "默认用户")));       //给Title设置标题
            } else {
                mTv_goback.setText(String.format("%s", view.getTitle()));
            }

            if (myProgressDialog != null && myProgressDialog.isShowing()) {
                //关闭下拉刷新控件的刷新状态//开启下拉刷新控件的刷新状态
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() { // 0.5秒后发送消息，停止刷新
                        disProgressD();
                    }
                }, 500);
            }

            super.onPageFinished(view, url);
        }


        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
//            if (request.getUrl().toString().contains("kapi/modul/info/uid")){
//
//            }

            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (url.contains("kapi/modul/info/uid")) {  //拦截网页内部3D模型的点击事件
                urlSplitMap = AppUtils.UrlSplitMap(url);
                try {
                    Message msg = new Message();
                    msg.what = R.id.doSuccess;
                    mHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            return super.shouldInterceptRequest(view, url);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e("===",url);
            url=url.replace("http://v7.u3d.xnku.com/","http://106.14.36.250/");
            view.loadUrl(url);
            return true;
        }
    }

}
